package LC;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lhn
 * @date 2024-09-18 16:30
 */

public class ZigzagConversion {
    public static void main(String[] args) {
        String s = "PAYPALISHIRING";
        System.out.println(convert(s, 3));
        System.out.println(convert(s, 4));
        System.out.println(convert(s, 5));
    }

    public static String convert(String s, int numRows) {
        if (numRows == 1) return s;
        List<StringBuilder> rows = new ArrayList<>();
        boolean flag = false;    // true: 向下，false: 向上
        for (int i = 0; i < numRows; i++) {
            rows.add(new StringBuilder());
        }
        char[] chars = s.toCharArray();
        int index = 0;
        for (char ch: chars
             ) {
            rows.get(index).append(ch);
            if (index % (numRows - 1) == 0) {
                //  第一次进来flag = false变为true
                flag = !flag;
            }
            if (flag) {
                // 向下
                index++;
            } else {
                // 向上
                index--;
            }
        }
//        for (int i = 0; i < numRows; i++) {
//            System.out.println("row " + i + ": " + rows.get(i));
//        }

        StringBuilder res = new StringBuilder();
        for (StringBuilder row: rows
             ) {
            res.append(row);
        }
        return res.toString();
    }
}
